import Vue from "vue"
import Vuex from "vuex"
import createPersistedState from "vuex-persistedstate"
import lodash from "lodash"
Vue.use(Vuex)

const emitState = function(store) {
  store.subscribe((mutation, state) => {
    console.log(mutation)
    if (["updateWidgets"].includes(mutation.type)) {
      window.H.hook.$emit("vuex:mutation", state)
    }
  })
}

export default new Vuex.Store({
  state: {
    widgets: [],
    widgetId: 0,
    currentWidget: null,
  },
  mutations: {
    updateWidgets(state, widget) {
      let _widgets = state.widgets.map(item => {
        if (item.id === widget.id) {
          item = lodash.merge(item, widget)
        }
        return item
      })
      state.widgets = _widgets
    },
    addWidget(state, widget) {
      state.widgets.push(widget)
    },
    replaceWidget(state, widgets) {
      state.widgets = widgets
    },
    increaseWidgetId(state) {
      state.widgetId++
    },
    updateCurrentWidget(state, widget) {
      state.currentWidget = widget
    },
  },
  actions: {
    AddWidget({ commit, state }, widget) {
      commit("increaseWidgetId")
      commit(
        "addWidget",
        Object.assign(widget, {
          title: "未命名" + state.widgetId,
          id: state.widgetId,
        })
      )
    },
    UpdateWidget({ commit }, widget) {
      commit("updateWidgets", widget)
    },
  },
  modules: {},
  plugins: [createPersistedState(), emitState],
})
